package com.gitee.kamismile.stoneComEx.common.exception.server;

import com.gitee.kamismile.stone.commmon.base.ResultVO;
import com.gitee.kamismile.stone.commmon.util.JsonUtil;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Controller;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OtherFluxExceptionHandler implements WebExceptionHandler {

    private static final Logger logger =  LoggerFactory.getLogger(OtherFluxExceptionHandler.class);


    private static final String ERROR_PATH = "/error";


    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ResultVO errorMsg = new ResultVO();
        errorMsg.setCode("-1");
        if (ex instanceof ResponseStatusException) {
            exchange.getResponse().setStatusCode(((ResponseStatusException) ex).getStatusCode());
            if (ex.getMessage() != null) {
                logger.error(ex.getMessage());
            }
            errorMsg.setMessage("page not found");
        } else {
            errorMsg.setMessage("error");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("code", errorMsg.getCode());
        result.put("message", errorMsg.getMessage());
        result.put("errors", Arrays.asList(errorMsg));

        byte[] bytes = JsonUtil.toJson(result).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
        return exchange.getResponse().writeAndFlushWith(Flux.just(Flux.just(buffer)));

    }
}
